<template>
  <div id="container"></div>
</template>

<script>
  import  * as  THREE from 'three'
  export default {
    name: "Streetscape",
    data(){
      return{
        camera:null,
        scene:null,
        renderer:null,
        raycaster: null,
        nextScene:null,
        mouse : null,	//将鼠标位置
        is_click:false,		//点击事件
        isUserInteracting : false,
        onMouseDownMouseX : 0,
        onMouseDownMouseY : 0,
        lon : 0,
        onMouseDownLon : 0,
        lat : 0,
        onMouseDownLat : 0,
        phi : 0,
        theta : 0,
        geometry:null,	//球体网格
        currentSceneMaterial:null,
        currentSceneMaterial_low:null,		//宿舍全景图材质
        nextSceneMaterial:null,
        nextSceneMaterial_low:null,
        nextSceneMaterial_flag : false,	//阳台全景图材质、转到阳台
        mesh:null,		//全景球体对象
        time : 0,	//加载计数
        camera_time : 0,//摄像机移动参数
        exchange_img : false,	//切换图片标志位

        onPointerDownPointerX :0,
        onPointerDownPointerY : 0,
        onPointerDownLon : 0,
        onPointerDownLat : 0,

        container:null,
        circle1_mesh : null,
        circle2_mesh : null,
        circle1_imageId : null,
        circle2_imageId : null,
        ///http://localhost:8080/StreetView_Service/GetPanoTile?TileID=00010007-01-20150802074859775-1-0-0-0
        getImageRootUrl : 'http://localhost:8080/StreetView_Service/GetPanoTile?TileID=',
        getImageTileID : "00010007-01-20150802074859775",
        getFirstImageDir : '-1-0-0-0',
        getSecondImageDir : '-1-3-',
        getThreeImageDir : '-1-4-',
        getImageTileID : '00010007-01-20150802075209175'
      }
    },
    mounted(){
      this.$nextTick(function () {
        this.init();
        this.animate();
      })
    },
    methods:{
      init(){
        this.raycaster=new THREE.Raycaster();
        this.mouse=new THREE.Vector2();
        this.container = document.getElementById('container');
        this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1100);
        this.camera.target = new THREE.Vector3(0, 0, 0);
        this.scene = new THREE.Scene();
        //全景场景
        this.geometry = new THREE.SphereGeometry(500, 60, 40);

        this.geometry.scale(- 1, 1, 1);

        ///初始化第一张图片 根据坐标
        this.InitSceneCoord('119.25599098205566', '33.789990528800494');

        document.addEventListener('mousedown', this.onDocumentMouseDown, false);
        document.addEventListener('mousemove', this.onDocumentMouseMove, false);
        document.addEventListener('mouseup', this.onDocumentMouseUp, false);
        document.addEventListener('wheel', this.onDocumentMouseWheel, false);
        document.addEventListener('touchstart', this.onDocumentTouchDown, false);
        document.addEventListener('touchmove', this.onDocumentTouchMove, false);
        document.addEventListener('touchend', this.onDocumentMouseUp, false);
        window.addEventListener('resize', this.onWindowResize, false);
      },

      animate() {
        requestAnimationFrame(this.animate);
        if (!this.renderer) return;

        this.lat = Math.max(- 85, Math.min(85, this.lat));
        this.phi = THREE.Math.degToRad(90 - this.lat);
        this.theta = THREE.Math.degToRad(this.lon);

        this.camera.target.x = 500 * Math.sin(this.phi) * Math.cos(this.theta);
        this.camera.target.y = 500 * Math.cos(this.phi);
        this.camera.target.z = 500 * Math.sin(this.phi) * Math.sin(this.theta);

        this.camera.lookAt(this.camera.target);

        if (this.camera_time > 0 && this.camera_time < 50) {
          this.camera.target.x = -493;
          this.camera.target.y = -28;
          this.camera.target.z = -72;
          this.camera.lookAt(this.camera.target);
          this.camera.fov -= 1;
          this.camera.updateProjectionMatrix();	//需要更新，不自动更新
          this.camera_time++;
          this.nextScene.visible = false;
        } else if (this.camera_time == 50) {
          this.lat = -2;
          this.lon = 182;
          this.camera_time = 0;
          this.camera.fov = 75;
          this.camera.updateProjectionMatrix();
        }
        this.renderer.render(this.scene, this.camera);
      },

      InitSceneCoord(lon, lat){
        //'119.25599098205566', '33.789990528800494'
        var that=this;
        this.getInitImageByCoord(lon, lat, function (data) {
          that.getImageTileID = data.GetPanoInfoResult.ImageInfo.ImageID;
          that.currentSceneMaterial_low = new THREE.MeshBasicMaterial({
            //http://localhost:8080/StreetView_Service/GetPanoTile?TileID=00010007-01-20150802074859775-1-0-0-0
            map: new THREE.TextureLoader().load(that.getImageRootUrl + that.getImageTileID + that.getFirstImageDir, void function () {
              that.time++
            }())
          });

          that.getSecondTexturesFromAtlasFile();
          that.mesh = new THREE.Mesh(that.geometry, that.currentSceneMaterial_low);
          that.scene.add(that.mesh);
          that.renderer = new THREE.WebGLRenderer();
          that.renderer.setPixelRatio(window.devicePixelRatio);
          that.renderer.setSize(window.innerWidth, window.innerHeight);
          that.container.appendChild(that.renderer.domElement);
          var links = data.GetPanoInfoResult.Links;
          // //下一个场景
          if (links.length == 2) {
            that.scene.remove(that.circle1_mesh);
            that.circle1_mesh = new THREE.Mesh(
              new THREE.CircleGeometry(0.3, 30, 0, 2 * Math.PI),
              new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.DoubleSide })
            );
            that.circle1_mesh.rotation.x = 80;
            that.circle1_mesh.rotation.y = 70;
            that.circle1_mesh.position.set(4, -1.6, -0.0);
            that.scene.add(that.circle1_mesh);
            that.circle1_imageId = links[0].ImageID;
            // //前一个场景
            that.scene.remove(that.circle2_mesh);
            that.circle2_mesh = new THREE.Mesh(
              new THREE.CircleGeometry(0.4, 30, 0, 2 * Math.PI),
              new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.DoubleSide })
            );
            that.circle2_mesh.rotation.x = 80;
            that.circle2_mesh.rotation.y = 70;
            that.circle2_mesh.position.set(6, -1.5, -0.0);
            that.scene.add(that.circle2_mesh);
            that.circle2_imageId = links[1].ImageID;
          }
          console.log(that.camera.target)
        });
      },

      InitScenePanoID() {
        var that=this;
        this.currentSceneMaterial_low = new THREE.MeshBasicMaterial({
          //http://localhost:8080/StreetView_Service/GetPanoTile?TileID=00010007-01-20150802074859775-1-0-0-0
          map: new THREE.TextureLoader().load(this.getImageRootUrl + this.getImageTileID + this.getFirstImageDir, void function () {
            that.time++
          }())
        });

        this.mesh.material = this.currentSceneMaterial_low;
        this.getSecondTexturesFromAtlasFile();
        this.getImagePano(this.getImageTileID, function (data) {
          var links = data.GetPanoInfoResult.Links;

          // //下一个场景
          if (links.length == 2) {

            that.circle1_imageId = links[0].ImageID;

            that.circle2_imageId = links[1].ImageID;
          }
        });
      },

      getSecondTexturesFromAtlasFile(){
        ///http://localhost:8080/StreetView_Service/GetPanoTile?TileID=00010007-01-20150802074859775-1-3-
        var imageRootUrl = this.getImageRootUrl + this.getImageTileID + this.getSecondImageDir;
        var that=this;
        var canvas = null, context = null;
        var num = 0;
        var imgs = [];
        for (var i = 0; i < 4; i++) {
          for (var j = 0; j < 8; j++) {
            var imageUrl = imageRootUrl + i + '-' + j;
            var imageObj = new Image();
            (function (i, j, imageObj) {
              imageObj.onload = function () {
                var imgWidth = imageObj.width;
                var imgHeight = imageObj.height;
                var tileWidth = 4096;
                var tileHeight = 2048;
                {
                  num++;
                  if (num == 32) {
                    if (canvas == null) {
                      canvas = document.createElement('canvas');
                      context = canvas.getContext('2d');
                      canvas.height = tileHeight;
                      canvas.width = tileWidth;
                    }
                    for (var k = 0; k < imgs.length; k++) {
                      context.drawImage(imgs[k], 0, 0, imgWidth, imgHeight, imgWidth * (k % 8), imgHeight * Math.floor(k / 8), imgWidth, imgHeight);
                    }
                    var cstexture = new THREE.Texture(canvas);
                    cstexture.needsUpdate = true;
                    that.currentSceneMaterial = new THREE.MeshBasicMaterial({
                      map: cstexture
                    });
                    that.mesh.material = that.currentSceneMaterial;
                    console.log('second');
                  }
                }
              };
            })(i, j, imageObj);
            imageObj.setAttribute('crossOrigin', 'Anonymous');
            imageObj.src = imageUrl;
            imgs.push(imageObj);
          }
        }
      },

      getThreeTexturesFromAtlasFile(){
        /// http://localhost:8080/StreetView_Service/GetPanoTile?TileID=00010007-01-20150802074859775-1-4-
        var imageRootUrl = this.getImageRootUrl + this.getImageTileID + this.getThreeImageDir;
        var that=this;
        var canvas = null, context = null;
        var num = 0;
        var imgs = [];
        for (var i = 0; i < 8; i++) {
          for (var j = 0; j < 16; j++) {
            var imageUrl = imageRootUrl + i + '-' + j;
            var imageObj = new Image();
            (function (i, j, imageObj) {
              imageObj.onload = function () {
                var imgWidth = imageObj.width;
                var imgHeight = imageObj.height;
                var tileWidth = 8192;
                var tileHeight = 4096;
                {
                  num++;
                  if (num == 128) {
                    if (canvas == null) {
                      canvas = document.createElement('canvas');
                      context = canvas.getContext('2d');
                      canvas.height = tileHeight;
                      canvas.width = tileWidth;
                    }
                    for (var k = 0; k < imgs.length; k++) {
                      context.drawImage(imgs[k], 0, 0, imgWidth, imgHeight, imgWidth * (k % 16), imgHeight * Math.floor(k / 16), imgWidth, imgHeight);
                    }
                    var cstexture = new THREE.Texture(canvas);
                    cstexture.needsUpdate = true;
                    that.currentSceneMaterial = new THREE.MeshBasicMaterial({
                      map: cstexture
                    });
                    that.mesh.material = that.currentSceneMaterial;

                    console.log('three');
                  }
                }
              };
            })(i, j, imageObj);
            imageObj.setAttribute('crossOrigin', 'Anonymous');
            imageObj.src = imageUrl;
            imgs.push(imageObj);
          }
        }
      },

      getInitImageByCoord(log, lat,callback){
        var url = 'http://localhost:8080/StreetView_Service/GetPanoInfo?MethodType=2&ToleratePano=0&L=' + log + '&f=json&ViewType=1&Type=0&B=' + lat + '&PanoID=-1&TolerateBL=0.002&TolerateFacade=200';
        $.ajax({
          url: url,
          type: 'get',
          dataType: 'json',
          success: function (data) {
            console.log(data);
            //getImageTileID=data.GetPanoInfoResult.ImageInfo.ImageID;

            // Angle: 0.02448116490780312
            // ImageID: "00010007-01-20150802075208122"
            // SegmentID: "20150802-05-080010365-00000000"
            // SegmentIndex: 156
            // Type: 1
            // X: 431233.14415812795
            // Y: 3740619.215678921
            // Z: 18.35638091664121

            //links=data.GetPanoInfoResult.Links
            if(typeof callback =='function')
            {
              callback(data);
            }
          },
          error: function (s1, s2, s3) {

          }
        })
      },

      getImagePano(PanoID,callback){
        var url = 'http://localhost:8080/StreetView_Service/GetPanoInfo?Type=0&TolerateFacade=200&ToleratePano=0&ViewType=1&MethodType=0&f=json&PanoID=' + PanoID;
        $.ajax({
          url:url,
          type:'get',
          dataType:'json',
          success:function(data){
            if(typeof callback =='function')
            {
              callback(data);
            }
          }
        })
      },

      onDocumentMouseDown(event) {

        event.preventDefault();

        this.raycaster.setFromCamera(this.mouse, this.camera);   //射线捕捉
        var intersects = this.raycaster.intersectObjects([this.circle1_mesh]);
        var intersects2 = this.raycaster.intersectObjects([this.circle2_mesh]);
        // if (intersects.length > 0 && time ==2) {

        if (intersects.length > 0) {
          // changeScene();
          this.getImageTileID=this.circle1_imageId;
          this.InitScenePanoID();
        }
        else if (intersects2.length > 0) {
          this.getImageTileID=this.circle2_imageId;
          this.InitScenePanoID();
        }
        this.isUserInteracting = true;
        this.is_click = true;
        this.onPointerDownPointerX = event.clientX;
        this.onPointerDownPointerY = event.clientY;


        this.onPointerDownLon = this.lon;
        this.onPointerDownLat = this.lat;

      },

      onDocumentTouchDown(event) {
        event.preventDefault();

        this.isUserInteracting = true;
        this.onPointerDownPointerX = event.touches[0].pageX;
        this.onPointerDownPointerY = event.touches[0].pageY;


        this.onPointerDownLon = this.lon;
        this.onPointerDownLat = this.lat;
      },

      onDocumentMouseMove(event) {
        //  console.log("tex", sushe);
        //屏幕位置转换到3D世界坐标系
        this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        this.mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
        if (this.isUserInteracting === true) {
          this.lon = (this.onPointerDownPointerX - event.clientX) * 0.1 + this.onPointerDownLon;
          this.lat = (event.clientY - this.onPointerDownPointerY) * 0.1 + this.onPointerDownLat;
        }
      },

      //手机控制适配
      onDocumentTouchMove(event) {

        if (this.isUserInteracting === true) {
          this.lon = (this.onPointerDownPointerX - event.touches[0].pageX) * 0.1 + this.onPointerDownLon;
          this.lat = (event.touches[0].pageY - this.onPointerDownPointerY) * 0.1 + this.onPointerDownLat;
        }
      },

      onDocumentMouseUp(event) {
        this.isUserInteracting = false;
      },

      onDocumentMouseWheel(event) {
        var tempfov = this.camera.fov + event.deltaY * 0.03;
        if (tempfov >= 55 && tempfov <= 100) {
          this.camera.fov += event.deltaY * 0.05;
          this.camera.updateProjectionMatrix();
          if (tempfov <= 60) {
            this.getThreeTexturesFromAtlasFile();
          }
          else {
            this.getSecondTexturesFromAtlasFile();
          }
        }
      },

      onWindowResize() {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(window.innerWidth, window.innerHeight);

      },
    }
  }
</script>

<style scoped>
  body {
    background-color: #000000;
    margin: 0px;
    overflow: hidden;
  }

  #info {
    position: absolute;
    top: 0px;
    width: 100%;
    color: #ffffff;
    padding: 5px;
    font-family: Monospace;
    font-size: 13px;
    font-weight: bold;
    text-align: center;
  }

  a {
    color: #ffffff;
  }
</style>
